package com.wl.other.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.entity.Message;
import com.wl.other.biz.IMessageBiz;
import com.wl.other.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MessageBizImpl extends ServiceImpl<MessageMapper, Message> implements IMessageBiz {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public int add(Message message) {
        message.setCtime(LocalDateTime.now());
        message.setRead(0);
        return messageMapper.insert(message);
    }

    @Override
    public List<Message> getChatHistory(int senderId, int receiverId) {
        //查询双方所有聊天记录，按时间顺序排列
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .and(wrapper -> wrapper
                        .eq(Message::getSid, senderId)
                        .eq(Message::getRid, receiverId))
                .or(wrapper -> wrapper
                        .eq(Message::getSid, receiverId)
                        .eq(Message::getRid, senderId))
                .orderByAsc(Message::getCtime);
        return this.list(queryWrapper);
    }

    @Override
    public int getUnreadCount(int userId) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Message::getRid, userId)
                .eq(Message::getRead, 0);
        return (int) this.count(queryWrapper);
    }

    @Override
    public boolean markAsRead(List<Integer> messageIds) {
        if (messageIds == null || messageIds.isEmpty()) return false;

        UpdateWrapper<Message> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .in("mid", messageIds)
                .set("`read`", 1); // 添加反引号转义

        return this.update(updateWrapper);
    }

    @Override
    public List<Integer> getContactList(int userId) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT CASE WHEN sid = " + userId + " THEN rid ELSE sid END as contactId")
                .eq("sid", userId).or().eq("rid", userId);

        return baseMapper.selectObjs(queryWrapper).stream()
                .filter(Objects::nonNull)
                .map(obj -> ((Number) obj).intValue()) // 安全转换
                .collect(Collectors.toList());
    }
}
